package com.hcinfos.gsoo.ui;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hcinfos.gsoo.R;
import com.hcinfos.gsoo.adapter.ContactAdapter;
import com.hcinfos.gsoo.config.Common;
import com.hcinfos.gsoo.enity.PhoneContact;

/**
 * 推荐给好友
 * 
 * @author john
 * 
 */
public class IntroFriendActivity extends Activity implements OnClickListener {

	private TextView reg_tv;
	private ImageButton left_ib;
	private TextView center_tv;
	private EditText phone_et;
	private ImageView add_iv;
	private EditText intr_et;
	private Button send_button;

	private Dialog contactDialog;
	private ListView listView;
	private ContactAdapter adapter;
	private List<PhoneContact> contactList;
	private TextView tip_tv;

	private String phoneNumStr;
	public final int OBTAIN_CONTACT_SUCCESS = 0x1120;
	private SmsManager smsManager;
	private Context context;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		IntentFilter intentFilter = new IntentFilter("SENT_SMS_ACTION");
		registerReceiver(smsReceiver, intentFilter);
		smsManager = SmsManager.getDefault();
		context = this;
		setContentView(R.layout.activity_introfriend);
		contactList = new ArrayList<PhoneContact>();
		initRes();
		new Thread(new Runnable() {

			@Override
			public void run() {
				getPhoneContact();
			}
		}).start();

	}

	private void initRes() {
		left_ib = (ImageButton) findViewById(R.id.left_ib);
		left_ib.setOnClickListener(this);
		reg_tv = (TextView) findViewById(R.id.reg_tv);
		reg_tv.setVisibility(View.GONE);
		center_tv = (TextView) findViewById(R.id.center_tv);
		center_tv.setText("推荐给好友");

		phone_et = (EditText) findViewById(R.id.phone_edit);
		add_iv = (ImageView) findViewById(R.id.add_iv);
		add_iv.setOnClickListener(this);

		intr_et = (EditText) findViewById(R.id.intr_et);
		intr_et.setText("#Gsoo客户端#可以查看周围海量信息,又方便又有优惠哦，"
				+ "并且不知道附近的有哪些商家信息可以使用搜信在线求助!,既好玩，"
				+ "又实惠推荐给大家试试http://www.gsoo.com/apps/android/v1.1/gsoo.apk");
		send_button = (Button) findViewById(R.id.send_button);
		send_button.setOnClickListener(this);
		initContactDialog();
	}

	private void initContactDialog() {

		LayoutInflater inflater = getLayoutInflater();
		RelativeLayout dialog_rl = (RelativeLayout) inflater.inflate(
				R.layout.contact_list_view, null);
		listView = (ListView) dialog_rl.findViewById(R.id.listView);
		tip_tv = (TextView) dialog_rl.findViewById(R.id.tip_tv);
		adapter = new ContactAdapter(this, contactList);
		listView.setAdapter(adapter);
		contactDialog = new Dialog(this, R.style.QuitDialog);
		contactDialog.setContentView(dialog_rl);
		Window dialogWindow = contactDialog.getWindow();
		WindowManager.LayoutParams lp = dialogWindow.getAttributes();
		dialogWindow.setGravity(Gravity.CENTER);
		lp.width = (int) (280 * Common.PROPORTION); // 宽度
		lp.height = (int) (380 * Common.PROPORTION); // 高度
		dialogWindow.setAttributes(lp);

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				phoneNumStr = contactList.get(position).getPhoneNum();
				phone_et.setText(phoneNumStr);
				contactDialog.dismiss();
			}
		});
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.left_ib:
			finish();
			break;
		case R.id.add_iv:
			if (contactDialog != null)
				contactDialog.show();
			break;
		case R.id.send_button:
			if (phone_et.getText().toString().length() == 0) {
				Toast.makeText(this, "请先选择你要分享的联系人", 500).show();
				return;
			} else {
				sendMms();
			}
			break;
		}
	}

	private void sendMms() {
		Intent sentIntent = new Intent("SENT_SMS_ACTION");
		PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, sentIntent,
				0);
		List<String> divideContents = smsManager.divideMessage(intr_et
				.getText().toString());
		for (String text : divideContents) {
			smsManager.sendTextMessage(phone_et.getText().toString(), null,
					text, sentPI, null);
		}

	}

	BroadcastReceiver smsReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {

			switch (getResultCode()) {
			case Activity.RESULT_OK:
				phone_et.setText("");
				Toast.makeText(context, "短信发送成功", Toast.LENGTH_SHORT).show();
				break;
			case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
				break;
			case SmsManager.RESULT_ERROR_RADIO_OFF:
				break;
			case SmsManager.RESULT_ERROR_NULL_PDU:
				break;
			}
		}

	};

	protected void onDestroy() {
		if (smsReceiver != null)
			unregisterReceiver(smsReceiver);
		super.onDestroy();
	};

	private void getPhoneContact() {
		List<PhoneContact> list = new ArrayList<PhoneContact>();
		Cursor c = null;
		c = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
				null, null, null, null);
		while (c.moveToNext()) {
			PhoneContact contact = new PhoneContact();
			int index = c.getColumnIndex(PhoneLookup.DISPLAY_NAME);
			String name = c.getString(index);
			String id = c.getString(c
					.getColumnIndex(ContactsContract.Contacts._ID));
			Cursor phone = getContentResolver().query(
					ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
					null,
					ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = "
							+ id, null, null);
			contact.setName(name);
			Log.d("wxf", "name=" + name);
			while (phone.moveToNext()) {
				String number = phone
						.getString(phone
								.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
				contact.setPhoneNum(number);

			}
			list.add(contact);
			phone.close();

		}
		c.close();
		contactList.addAll(list);
		Message msg = handler.obtainMessage();
		msg.what = OBTAIN_CONTACT_SUCCESS;
		handler.sendMessage(msg);
	}

	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
			case OBTAIN_CONTACT_SUCCESS:

				if (contactList.size() == 0) {
					tip_tv.setVisibility(View.VISIBLE);
					tip_tv.setText("暂无联系人");
				} else {
					tip_tv.setVisibility(View.GONE);
				}
				adapter.setDataChange(contactList);
				break;
			}

		};
	};

}
